//
//  DHOrderDetailViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/16.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHOrderDetailViewController.h"
#import "DHOrderDetailAddressCell.h"
#import "DHOrderDetailLeaseCell.h"
#import "Address.h"
#import "DHContactViewController.h"
#import "DHOrderPayViewController.h"
#import "DHOrderDetail_SixCell.h"
#import "DHOrderDetail_CheckViewController.h"

@interface DHOrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet DHGradualButton *payButton;

@property (strong, nonatomic) Address *address;

@property (strong, nonatomic) NSArray *costsArr;

@property (assign, nonatomic) CGFloat totalPrice;

@property (assign, nonatomic) BOOL isSix; //是否是6小时送达城市

@end

@implementation DHOrderDetailViewController

//- (instancetype)initWithCartSelectedArr:(NSMutableArray *)selectedArr cartSelectedSizesArr:(NSMutableArray *)sizesArr
//{
//    self = [super init];
//    if (self) {
//        self.cartSelectedArr = selectedArr;
//        self.cartSlectedSizesArr = sizesArr;
//    }
//    return self;
//}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"订单详情";
    
    self.bottomView.layer.cornerRadius = 2;
    self.bottomView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.bottomView.layer.shadowRadius = 5;
    self.bottomView.layer.shadowOpacity = 0.5;
    self.bottomView.layer.shadowOffset  = CGSizeMake(0, 0);
    
    [self.payButton addTarget:self action:@selector(createOrder) forControlEvents:UIControlEventTouchUpInside];
    
    [self loadAddressRecent];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetailAddressCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetailAddressCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetailLeaseCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetailLeaseCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetail_SixCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetail_SixCell];
    
    addNObserver(@selector(changeAddress:), @"DHContactViewController");
    
}

- (void)dealloc{
    removeNObserver(@"DHContactViewController");
}

- (void)changeAddress:(NSNotification *)not{
    if (not){
        NSDictionary *dic = not.object;
        self.address = [dic objectForKey:@"address"];
        self.isSix = [[GlobalManager shareGlobalManager].supportCitiesArray containsObject:self.address.city];
        [self orderValid];
    }
}

// 获取地址
- (void)loadAddressRecent{
    [[DHNetAPIClient shareDHNetAPIClient] request_address_recentAndBlock:^(id data, NSError *error) {
        if ([data objectForKey:@"address"]) {
            self.address = [Address modelWithDictionary:[data objectForKey:@"address"]];
            self.isSix = [[GlobalManager shareGlobalManager].supportCitiesArray containsObject:self.address.city];
        }else{
            self.address = [[Address alloc] init];
            self.address.phone = [Login curLoginUser].phone;
            self.address.name = [[Login curLoginUser].realname length] > 0? [Login curLoginUser].realname:[Login curLoginUser].nickname;
            if ([[NSUserDefaults standardUserDefaults] objectForKey:USER_HOME_ADDRESS]) {
                GeoCode *geocode = [GeoCode modelWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:USER_HOME_ADDRESS]];
                self.address.province = geocode.province;
                self.address.city = geocode.city;
                self.address.district = geocode.district;
                self.address.address = geocode.address;
                self.address.logistic = @"普通快递";
                self.address.accurate = @"";
            }
        }
        [self.tableView reloadData];
        [self orderValid];
    }];
}

// 验证是否可创建订单
- (void)orderValid{
    if (!self.address || self.address.province.length == 0) {
        [NSObject showHudTipStr:@"请补充联系方式"];
        [self calculateOrderPayPrice];
        [self.tableView reloadData];
        return;
    }
    NSMutableArray *productIDArr = [NSMutableArray array];
    [self.cartSlectedSizesArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [productIDArr addObject:@{@"_id":obj[@"_id"]}];
    }];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@{@"leased":productIDArr} forKey:@"products"];
    if (self.address) {
        [params setObject:[NSDictionary entityToDictionary:self.address] forKey:@"consignee"];
    }
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_validWithParams:params andBlock:^(id data, NSError *error) {
        self.costsArr = [data objectForKey:@"costs"];
        [self calculateOrderPayPrice];
        [self.tableView reloadData];
    }];
}

// 计算订单支付金额
- (void)calculateOrderPayPrice{
    __block CGFloat payPrice = 0;
    [self.costsArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat cost_value = [[obj objectForKey:@"cost_value"] floatValue];
        if (cost_value >= 0) {
            payPrice += cost_value;
        }else{
            payPrice -= cost_value;
        }
    }];
    if (payPrice == 0) {
        [self.payButton setTitle:@"提交" forState:UIControlStateNormal];
    }
    self.totalPrice = payPrice;
    self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",payPrice];
}

// 提交订单
- (void)createOrder{
    if (self.address.name.length == 0 || self.address.province.length == 0) {
        [NSObject showHudTipStr:@"请补充联系方式"];
        return;
    }
    NSMutableArray *productIDArr = [NSMutableArray array];
    [self.cartSlectedSizesArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [productIDArr addObject:@{@"_id":obj[@"_id"]}];
    }];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@{@"leased":productIDArr} forKey:@"products"];
    if (self.address) {
        [params setObject:[NSDictionary entityToDictionary:self.address] forKey:@"consignee"];
    }
    self.payButton.enabled = NO;
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_createWithParams:params andBlock:^(id data, NSError *error) {
        self.payButton.enabled = YES;
        if ([self.payButton.titleLabel.text isEqualToString:@"支付"]) { // 创建订单后跳转到支付界面
            DHOrderPayViewController *orderPayController = [[DHOrderPayViewController alloc] initWithOrders:[data objectForKey:@"orders"] orderValidParams:params];
            [self.navigationController pushViewController:orderPayController animated:YES];
        }else if ([self.payButton.titleLabel.text isEqualToString:@"提交"]){ //创建订单后跳转到订单详情界面
            NSArray *orderArr = [data objectForKey:@"orders"];
            if (orderArr.count > 0) {
                NSDictionary *orderDic = orderArr[0];
                DHOrderDetail_CheckViewController *odController = [[DHOrderDetail_CheckViewController alloc] init];
                odController.orderID = [orderDic objectForKey:@"_id"];
                [self.navigationController pushViewController:odController animated:YES];
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma UITableViewDelegate and UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isSix) {
        return 3;
    }else{
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 82;
    }else if (indexPath.section == 2){
        return 100;
    }else{
        return 80 + self.cartSelectedArr.count * 30;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DHOrderDetailAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetailAddressCell forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",self.address.province? :@"",self.address.city? :@"",self.address.district? :@"",self.address.address? :@""];
        cell.phoneLabel.text = self.address.phone;
        cell.nameLabel.text = self.address.name;
        return cell;
    }else if (indexPath.section == 2){
        DHOrderDetail_SixCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetail_SixCell forIndexPath:indexPath];
        [cell.express_switch bk_addEventHandler:^(UISwitch *sender) {
            NSLog(@"选择");
            if (sender.on) {
                self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.totalPrice + 100];
            }else{
                self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.totalPrice];
            }
            
        } forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        DHOrderDetailLeaseCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetailLeaseCell forIndexPath:indexPath];
        [cell updateCellWithProduct:self.cartSelectedArr costDic:self.costsArr];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.1;
    }else{
        return 46;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 46)];
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, headerView.width - 14, headerView.height)];
        titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14];
        titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        titleLabel.text = @"订阅";
        [headerView addSubview:titleLabel];
        return headerView;
    }else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DHContactViewController *addressController = [[DHContactViewController alloc] init];
        addressController.address = self.address;
        [self.navigationController pushViewController:addressController animated:YES];
    }
}

@end
